use macroquad::prelude::{screen_height, screen_width, Font};

use crate::{
    post::{Post, PostWidget},
    user::UserCache,
    utils::intersects,
};

pub struct Feed {
    offset: f32,
    post_widgets: Vec<PostWidget>,
}

impl Feed {
    pub fn new(posts: &Vec<Post>, users: &UserCache) -> Self {
        return Self {
            offset: 0.0,
            post_widgets: posts.iter().map(|p| PostWidget::new(&p, users)).collect(),
        };
    }
    pub fn draw_feed(&mut self, font: Font) {
        let mut stack_bottom = self.offset;

        for pw in self.post_widgets.iter() {
            let post_height = pw.height();
            if intersects(
                (stack_bottom, stack_bottom + post_height),
                (0.0, screen_height()),
            ) {
                pw.draw(screen_width() / 2.0 - pw.width() / 2.0, stack_bottom, font);
            }
            stack_bottom += post_height;
        }
    }

    pub fn set_offset(&mut self, offset: f32) {
        let mut off = offset;
        let sum_height: f32 = self.post_widgets.iter().map(|p| p.height()).sum();

        off = off.max(-sum_height + screen_height());
        self.offset = off.min(0.0);
    }
    pub fn offset(&self) -> f32 {
        self.offset
    }
}
